package com.leectrl.adapter;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eclipsesource.v8.V8;
import com.eclipsesource.v8.V8Array;
import com.eclipsesource.v8.V8Object;
import com.hdl.school.entity.NormalSerialCode;
import com.hdl.school.utils.Logger;
import com.hdl.school.utils.RegExp;
import com.hdl.school.utils.StringUtil;
import com.leectrl.bean.QueueZigbeeCode;
import com.leectrl.bean.StatusParaserInfo;
import com.leectrl.bean.ZigbeeDevice;
import com.leectrl.bean.ZigbeeMessage;
import com.leectrl.utils.Bus;
import com.leectrl.utils.DbUtil;
import com.leectrl.utils.HexUtil;
import com.leectrl.utils.StorageManager;

import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AndroidSocketServerHandler implements Runnable {
    private Socket socket;
    private HashMap<String, ZigbeeDevice> zigbeeDeviceHashMap = new HashMap();
    private CopyOnWriteArrayList<QueueZigbeeCode> queueZigbeeCodes = new CopyOnWriteArrayList<>();
    Timer statusUploadTimer = null;
    Timer cmdSendTimer = null;
    private boolean running = true;


    public AndroidSocketServerHandler(Socket socket) {
        this.socket = socket;
        Log.e("TCP",socket.getInetAddress().toString());
        running = true;
        try {
            List<ZigbeeDevice> zigbeeDevices = DbUtil.getInstance().selector(ZigbeeDevice.class).findAll();
            if (zigbeeDevices != null) {
                for (ZigbeeDevice zigbeeDevice : zigbeeDevices) {
                    zigbeeDeviceHashMap.put(zigbeeDevice.getMac(), zigbeeDevice);
                }
            }

        } catch (DbException e) {
            e.printStackTrace();
        }

        startQueueRead();
        Bus.getInstance().on("zigbee_code", new Bus.MessageEvent() {
            @Override
            public void onEvent(String key, Object... message) {
                String mac = (String) message[0];
                NormalSerialCode normalSerialCode = (NormalSerialCode) message[1];
                sendTCPMessage(mac, normalSerialCode);
            }
        });
        Bus.getInstance().on("zigbee_dev_event", new Bus.MessageEvent() {
            @Override
            public void onEvent(String key, Object... message) {
                String action = (String) message[0];
                ZigbeeDevice zigbeeDevice = (ZigbeeDevice) message[1];
                if (action.equals("add")) {
                    zigbeeDeviceHashMap.put(zigbeeDevice.getMac(), zigbeeDevice);
                } else if (action.equals("del")) {
                    zigbeeDeviceHashMap.remove(zigbeeDevice.getMac());
                } else if (action.equals("update")) {
                    zigbeeDeviceHashMap.put(zigbeeDevice.getMac(), zigbeeDevice);
                }
            }
        });
        Bus.getInstance().emit("gateway-status", true);
        StorageManager.getInstance().setCacheItem("gatewayOnline","1");
        if (statusUploadTimer != null) {
            statusUploadTimer.cancel();
        }
        statusUploadTimer = new Timer();
        statusUploadTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                JSONObject jsonObject = new JSONObject();
                JSONObject statusObj = new JSONObject();
                jsonObject.put("action", "status_feedback");
                statusObj.put("zigbee-getway", "online");
                jsonObject.put("status", statusObj);
                Bus.getInstance().emit("publish_feedback_msg", jsonObject);
            }
        }, 1000, 5000);
        // 查询网络状态
        sendTCPMessage("2A 24 41 88 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0000 25 00 00 00 5C 12 05 00 01 01 30 23");
        sendTCPMessage(genMsg("0000000000000000", "5c12", "05", "01", "w"), 3000);
    }

    public void close() {
        Log.e("TCP","socket close");
        running = false;
        if (socket != null) {
            try {
                socket.close();
                socket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (statusUploadTimer != null) {
            statusUploadTimer.cancel();
            statusUploadTimer=null;
        }
        if(cmdSendTimer!=null){
            cmdSendTimer.cancel();
            cmdSendTimer=null;
        }
        StorageManager.getInstance().setCacheItem("gatewayOnline","0");
    }

    @Override
    public void run() {
        if (socket != null) {
            while (running) {
                try {
                    InputStream inputStream = socket.getInputStream();
                    byte[] buffer = new byte[1024];
                    int len = inputStream.read(buffer);
                    if (len != -1) {
                        byte[] bytes = Arrays.copyOfRange(buffer, 0, len);
                        String hex = HexUtil.bytes2HexString(bytes);
                        handleTCPMessage(hex);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    close();
                }
            }


        }

    }


    public void sendTCPMessage(String mac, NormalSerialCode normalSerialCode) {
        List<String> code = (List<String>) normalSerialCode.getCode();
        if (code == null || code.size() < 3) {
            return;
        }
        //Log.e("MqttService", "zigbee msg:zigbee_code:" + mac+","+code.get(2));
        for (int i = 0; i < 3; i++) {
            if (!HexUtil.isHexStr(code.get(i))) {
                Log.e("MqttService", code.get(i) + " is not hex");
                return;
            }
        }
        sendTCPMessage(genMsg(mac, code.get(0), code.get(1), HexUtil.reserveHex(code.get(2)), "w"), normalSerialCode.getDelay());
    }

    public void sendTCPMessage(String hex) {
        sendTCPMessage(hex, 0);
    }

    /**
     * 发送码，不实际发送，加入队列
     *
     * @param hex   需要发送的码
     * @param delay 延时
     */
    public void sendTCPMessage(String hex, int delay) {
        if (hex == null) {
            return;
        }
        hex = hex.replaceAll(" ", "");
        QueueZigbeeCode queueZigbeeCode = new QueueZigbeeCode(hex, System.currentTimeMillis() + delay);
        synchronized (queueZigbeeCodes) {
            if (queueZigbeeCodes.size() > 40) {
                queueZigbeeCodes.remove(0);
            }
            queueZigbeeCodes.add(queueZigbeeCode);
            queueZigbeeCodes.sort(new Comparator<QueueZigbeeCode>() {
                @Override
                public int compare(QueueZigbeeCode queueZigbeeCode, QueueZigbeeCode t1) {
                    return (int) (queueZigbeeCode.getTime() - t1.getTime());
                }
            });
        }

    }

    private void sendMessageToDevice(String hex) {
        byte[] respBytes = HexUtil.hexToByteArray(hex);
        if (socket != null && socket.isConnected()) {
            Log.e("MqttService", "zigbee msg:" + hex);
            try {
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(respBytes);
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    private void handleTCPMessage(String hex) {
        String hexStr = hex.toLowerCase();
        Log.e("zigbee rev:", hexStr);
        ZigbeeMessage zigbeeMessage = parseMsg(hexStr);
        if (zigbeeMessage == null) {
            return;
        }
        //  Log.e("zigbee rev:", JSON.toJSONString(zigbeeMessage));
        onReceiveZigbeeResp(zigbeeMessage);
        if ("25b8".equals(zigbeeMessage.getCmd())) {
            if ("ea03".equals(zigbeeMessage.getIndex()) && "09".equals(zigbeeMessage.getSub()) && zigbeeMessage.getData() == null) {
                sendTCPMessage(genMsg(null, "ea03", "09", Integer.toHexString((int) ((new Date()).getTime() / 1000)), "w"));
            } else if ("5c12".equals(zigbeeMessage.getIndex())) {
                if ("05".equals(zigbeeMessage.getSub())) {
                    if ("00".equals(zigbeeMessage.getData())) {
                        Logger.e("TCP", "建立网络成功");
                    } else {
                        Logger.e("TCP", "网络已建立");
                    }
                } else if ("07".equals(zigbeeMessage.getSub())) {
                    if ("00".equals(zigbeeMessage.getData())) {
                        Logger.e("TCP", "允许加入网络");
                    }
                }
            }
        } else if ("2098".equals(zigbeeMessage.getCmd())) {
            //自定义指令
            if (zigbeeMessage.getIndex().equals("b004")) {
                List<String> data = zigbeeMessage.getDataArr();
                ZigbeeDevice mZigbeeDevice = zigbeeDeviceHashMap.get(zigbeeMessage.getSource());

                if (zigbeeMessage.getDataArr() != null && zigbeeMessage.getDataArr().size() > 0) {
                    String regex = "2a[0-9a-z]{2}4188";
                    Pattern pattern = Pattern.compile(regex);
                    Matcher matcher = pattern.matcher(zigbeeMessage.getData());
                    if (matcher.find()) {
                        int startIndex = matcher.start();
                        if (zigbeeMessage.getData().length() < startIndex + 74) {
                            return;
                        }
                        String index = zigbeeMessage.getData().substring(startIndex + 64, startIndex + 68);
                        int dataLen = Integer.parseInt(zigbeeMessage.getData().substring(startIndex + 72, startIndex + 74), 16);
                        if (index.equals("a00f")) {
                            if (zigbeeMessage.getData().length() < startIndex + 74 + 2 * dataLen) {
                                return;
                            }
                            String playloadData = zigbeeMessage.getData().substring(startIndex + 74, startIndex + 74 + 2 * dataLen);
                            Logger.e("收到透传数据:" + playloadData);
                            if ((new RegExp("^fd[0-9a-f]{8,}efff$")).test(playloadData)&&mZigbeeDevice!=null) {
                                //空调控制器返回码，上传到服务器
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("action", "airctrl_setting_resp");
                                jsonObject.put("code", playloadData);
                                jsonObject.put("type", "zigbee");
                                jsonObject.put("mac", zigbeeMessage.getSource());
                                Bus.getInstance().emit("publish_feedback_msg", jsonObject);
                                List<StatusParaserInfo> statusParaserInfos = new ArrayList<>();
                                statusParaserInfos.add(new StatusParaserInfo("^fd[0-9a-z]{2}010034[0-9a-z]{46,}efff$", "var outputObj = {};var revCode = '{$revCode}';var devKey = '{$devKey}';var fanStatus = revCode.substring(39, 40);var powerStatus = revCode.substring(38, 39);outputObj['aircontroller_'+devKey] = JSON.stringify({status: fanStatus == \"1\" ? \"on\" : (powerStatus == \"0\" ? \"offline\" : \"off\"), fanOpen:fanStatus == \"1\", powerOpen:powerStatus == \"1\", temperature: parseInt(revCode.substring(16, 20), 16)/10, people: revCode.substring(40, 44)==\"0001\", humidity: parseInt(revCode.substring(20, 24), 16)/10, buzzer: revCode.substring(44, 48)==\"0001\"});outputObj['air_ctrl_power_'+devKey] = JSON.stringify({electricity:(parseInt(revCode.substring(24, 28), 16)/1000).toFixed(3),voltage:parseInt(revCode.substring(28, 32),16),power:parseInt(revCode.substring(32, 36),16)});outputObj;"));
                                statusParaserInfos.add(new StatusParaserInfo("^fd[0-9a-z]{2}01003f[0-9a-z]{22}efff$", "var outputObj = {};var revCode = '{$revCode}';var devKey = '{$devKey}';outputObj['air_ctrl_energy_'+devKey] = JSON.stringify({energy:parseInt(revCode.substring(20, 24), 16),during:parseInt(revCode.substring(24, 28),16)});outputObj;"));
                                for (StatusParaserInfo sp : statusParaserInfos) {
                                    if ((new RegExp(sp.getMatchRegex())).test(playloadData)) {
                                        try {
                                            V8 runtime = V8.createV8Runtime();
                                            V8Object parsedObj = runtime.executeObjectScript(sp.getParseCode().replace("{$revCode}", playloadData).replace("{$devKey}", mZigbeeDevice.getDevicekey()));
                                            V8Object json = runtime.getObject("JSON");
                                            V8Array args = new V8Array(runtime).push(parsedObj);
                                            String result = (String) json.executeFunction("stringify", args);
                                            args.release();
                                            json.release();
                                            parsedObj.release();
                                            runtime.release();
                                            JSONObject outputObj = JSON.parseObject(result);
                                            feedbackStatus(outputObj);
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }


                                        break;
                                    }
                                }
                            }else{
                        //        sendTCPMessage(genMsg(zigbeeMessage.getSource(), "B004", "00", HexUtil.reserveHex("040100906311050102" + StringUtil.padNum(Integer.toHexString(playloadData.length() / 2), 2) + playloadData), "w"), 3000);
                            }
                        }
                    }
                    List<String> dataArr = zigbeeMessage.getDataArr();
                    if (dataArr != null && dataArr.size() > 0) {
                        ZigbeeMessage innerMsg = parseMsg(dataArr.get(0));
                        if (innerMsg != null && innerMsg.getIndex().equals("0000")) {
                            handleTCPMessage(dataArr.get(0));
                            // return;
                        }
                    }


                }
                if (mZigbeeDevice == null) {
                    return;
                }
                synchronized (mZigbeeDevice){
                    if ("zigbee-switcher".equals(mZigbeeDevice.getDeviceType()) || "zigbee-switcher-s".equals(mZigbeeDevice.getDeviceType()) || "zigbee-switcher-t".equals(mZigbeeDevice.getDeviceType())) {
                        String keyStr = mZigbeeDevice.getDevicekey();
                        if ((keyStr == null) || keyStr.length() == 0) {
                            return;
                        }
                        String[] devKeys = null;
                        if (keyStr.indexOf("_") > 0) {
                            devKeys = keyStr.split("_");
                        } else if (keyStr.indexOf(",") > 0) {
                            devKeys = keyStr.split(",");
                        } else {
                            devKeys = new String[]{keyStr};
                        }
                        if (devKeys == null || devKeys.length == 0) {
                            return;
                        }
                        JSONObject light = new JSONObject();
                        JSONObject statusObj = new JSONObject();
                        if (data.size() > 0&&data.get(0).length()>=78) {
                            String tag1 = data.get(0).substring(64, 68);
                            light.put(tag1, data.get(0).substring(76, 78));
                        }
                        if (data.size() == 3&&data.get(2).length()>=78) {
                            String tag2 = data.get(2).substring(64, 68);
                            light.put(tag2, data.get(2).substring(76, 78));
                        }
                        if (light.containsKey("c12b")) {
                            statusObj.put("light_" + devKeys[0], (light.get("c12b").equals("01") ? "on" : "off"));
                        }
                        if (light.containsKey("c22b")&&devKeys.length>1) {
                            statusObj.put("light_" + devKeys[1], (light.get("c22b").equals("01") ? "on" : "off"));
                        }
                        if (light.containsKey("c32b")&&devKeys.length>2) {
                            statusObj.put("light_" + devKeys[2], (light.get("c32b").equals("01") ? "on" : "off"));
                        }
                        feedbackStatus(statusObj);

                    }else if ("zigbee-fan".equals(mZigbeeDevice.getDeviceType()) || "zigbee-fan-s".equals(mZigbeeDevice.getDeviceType()) || "zigbee-fan-t".equals(mZigbeeDevice.getDeviceType())) {
                        String keyStr = mZigbeeDevice.getDevicekey();
                        if ((keyStr == null) || keyStr.length() == 0) {
                            return;
                        }
                        String[] devKeys = null;
                        if (keyStr.indexOf("_") > 0) {
                            devKeys = keyStr.split("_");
                        } else if (keyStr.indexOf(",") > 0) {
                            devKeys = keyStr.split(",");
                        } else {
                            devKeys = new String[]{keyStr};
                        }
                        if (devKeys == null || devKeys.length == 0) {
                            return;
                        }
                        JSONObject light = new JSONObject();
                        JSONObject statusObj = new JSONObject();
                        if (data.size() > 0&&data.get(0).length()>=78) {
                            String tag1 = data.get(0).substring(64, 68);
                            light.put(tag1, data.get(0).substring(76, 78));
                        }
                        if (data.size() == 3&&data.get(2).length()>=78) {
                            String tag2 = data.get(2).substring(64, 68);
                            light.put(tag2, data.get(2).substring(76, 78));
                        }
                        if (light.containsKey("c12b")) {
                            statusObj.put("fan_" + devKeys[0], (light.get("c12b").equals("01") ? "on" : "off"));
                        }
                        if (light.containsKey("c22b")&&devKeys.length>1) {
                            statusObj.put("fan_" + devKeys[1], (light.get("c22b").equals("01") ? "on" : "off"));
                        }
                        if (light.containsKey("c32b")&&devKeys.length>2) {
                            statusObj.put("fan_" + devKeys[2], (light.get("c32b").equals("01") ? "on" : "off"));
                        }
                        feedbackStatus(statusObj);

                    } else if ("zigbee-curtain".equals(mZigbeeDevice.getDeviceType())) {
                        String keyStr = mZigbeeDevice.getDevicekey();
                        if ((keyStr == null) || keyStr.length() == 0) {
                            return;
                        }
                        if (data.size() > 0&&data.get(0).length()>=76) {
                            String tag = data.get(0).substring(68, 70);
                            if (tag.equals("00")) {
                                //电机状态
                                int openPercentage = Integer.parseInt(data.get(0).substring(74, 76), 16);
                                JSONObject statusObj = new JSONObject();
                                JSONObject statusInfo = new JSONObject();
                                if (openPercentage != 18) {
                                    openPercentage = 100 - openPercentage;
                                    //liuyong12124444845
                                    statusInfo.put("status", openPercentage < 20 ? "on" : "off");
                                    statusInfo.put("percentage", openPercentage);
                                    statusObj.put("curtain_" + keyStr, JSON.toJSONString(statusInfo));
                                    feedbackStatus(statusObj);
                                }

                            }

                        }
                    }
                }

            } else if ("0000".equals(zigbeeMessage.getIndex())) {
                if (zigbeeMessage.getSub().equals("00")) {
                    Logger.e(zigbeeMessage.getSource() + "入网成功", zigbeeMessage.getSourceCode());
                    //关闭入网
                    sendTCPMessage(genMsg(zigbeeMessage.getSource(), "5c12", "07", HexUtil.reserveHex("00"), "w"));
                    //5秒上报状
                    sendTCPMessage(genMsg(zigbeeMessage.getSource(), "0807", "00", HexUtil.reserveHex("0600010100000500100000000000"), "w"));
                    sendTCPMessage(genMsg(zigbeeMessage.getSource(), "0807", "00", HexUtil.reserveHex("0600020100000500100000000000"), "w"));
                    sendTCPMessage(genMsg(zigbeeMessage.getSource(), "0807", "00", HexUtil.reserveHex("0600030100000500100000000000"), "w"));
                }
            }
        } else if ("20b8".equals(zigbeeMessage.getCmd())) {
            //设备离网
            if ("f203".equals(zigbeeMessage.getIndex()) && "02".equals(zigbeeMessage.getSub())) {
                //查找课室内的设备
                if (zigbeeDeviceHashMap.containsKey(zigbeeMessage.getSource())) {
                    ZigbeeDevice mZigbeeDevice = zigbeeDeviceHashMap.get(zigbeeMessage.getSource());
                    try {
                        DbUtil.getInstance().delete(ZigbeeDevice.class, WhereBuilder.b("id", "=", mZigbeeDevice.getId()));
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    zigbeeDeviceHashMap.remove(zigbeeMessage.getSource());
                }
            }
        }
    }


    private void feedbackStatus(JSONObject statusObj) {
        Bus.getInstance().emit("status_feedback", statusObj);
        JSONObject msgObj = new JSONObject();
        msgObj.put("action", "status_feedback");
        msgObj.put("status", statusObj);
        Bus.getInstance().emit("publish_feedback_msg", msgObj);
    }


    /**
     * 解析收到的数据
     */
    private ZigbeeMessage parseMsg(String rev) {
        if (rev == null || rev.length() < 70) {
            return null;
        }
        ZigbeeMessage zigbeeMessage = new ZigbeeMessage();
        zigbeeMessage.setSourceCode(rev);
        zigbeeMessage.setHeader(rev.substring(0, 2));
        zigbeeMessage.setCmd(rev.substring(56, 60));
        zigbeeMessage.setTarget(rev.substring(36, 52));
        zigbeeMessage.setGroup(rev.substring(60, 64));
        zigbeeMessage.setIndex(rev.substring(64, 68));
        zigbeeMessage.setSource(rev.substring(20, 36));
        zigbeeMessage.setControl(HexUtil.reserveHex(rev.substring(4, 8)));
        zigbeeMessage.setSub(rev.substring(68, 70));
        if (rev.length() > 78) {
            String data = rev.substring(74, rev.length() - 4);
            zigbeeMessage.setData(data);
            List<String> dataArr = new ArrayList();
            String subStr = data;
            int startIndex = 0;
            while (startIndex >= 0) {
                startIndex = subStr.indexOf("2a");
                if (startIndex >= 0 && subStr.length() > startIndex + 20 && subStr.substring(startIndex + 4, startIndex + 20).equals("4188000000000000")) {
                    int endIndex = startIndex + Integer.parseInt(subStr.substring(startIndex + 2, startIndex + 4), 16) * 2 + 32;
                    if (endIndex > subStr.length()) {
                        endIndex = subStr.length();
                    }
                    dataArr.add(subStr.substring(startIndex, endIndex));
                    subStr = subStr.substring(endIndex);
                } else {
                    if (subStr.length() <= 2) {
                        startIndex = -1;
                    } else {
                        subStr = subStr.substring(startIndex + 2);
                        if (subStr.indexOf("2a") < 0) {
                            startIndex = -1;
                        }
                    }


                }
            }
            zigbeeMessage.setDataArr(dataArr);
        }
        return zigbeeMessage;
    }

    /**
     * 计算校验和
     *
     * @param payload
     * @returns {string}
     */
    private String genCheckTotal(String payload) {
        int total = 0;
        int len = payload.length() / 2;
        for (int i = 0; i < len; i++) {
            total += Integer.parseInt(payload.substring(i * 2, (i + 1) * 2), 16);
        }
        String totalHex = Integer.toHexString(total);
        if (totalHex.length() < 1) {
            totalHex = "0" + totalHex;
        } else {
            totalHex = totalHex.substring(totalHex.length() - 2);
        }
        return totalHex;
    }

    /***
     * 封装指令
     * 格式如2a27418800000000000000000000000000000000000000000000000025000000ea0309000489ca6826c923
     * @param mac
     * @param msg
     */
    private String genMsg(String mac, String index, String subIndex, String msg, String rw) {
        String mMsg = msg;
        if (msg.length() % 2 == 1) {
            mMsg = '0' + mMsg;
        }
        mMsg = HexUtil.reserveHex(mMsg);
        String payloadContent = "41880000000000000000000000000000" + (mac != null ? mac : "0000000000000000") + "0000" + (rw.equals("w") ? "25" : "20") + "000000" + index + StringUtil.padNum(subIndex, 2) + "00" + (mMsg != null && mMsg.length() > 0 ? (StringUtil.padNum(Integer.toHexString(mMsg.length() / 2), 2) + mMsg) : "");
        String cmdHex = "2a" + StringUtil.padNum(Integer.toHexString(payloadContent.length() / 2), 2) + payloadContent + genCheckTotal(payloadContent) + "23";
        cmdHex = cmdHex.toLowerCase();
        // console.log("发送:" + cmdHex)
        return cmdHex;
    }


    private void onReceiveZigbeeResp(ZigbeeMessage revObj) {
        Bus.getInstance().emit("zigbee_resp", JSON.toJSONString(revObj));
        if ("5c12".equals(revObj.getIndex())) {
            if ("07".equals(revObj.getSub())) {
                if ("00".equals(revObj.getData()) ) {
                    JSONObject msg=new JSONObject();
                    msg.put("action","zigbee");
                    msg.put("type","allowJoinSuccess");
                    sendBroadcast(JSON.toJSONString(msg).getBytes());
                }
            }
        } else if ("2098".equals(revObj.getCmd())) {
            if ("0000".equals(revObj.getIndex())) {
                if ("00".equals(revObj.getSub())) {
                    JSONObject msg=new JSONObject();
                    msg.put("action","zigbee");
                    msg.put("type","joined");
                    msg.put("mac",revObj.getSource());
                    sendBroadcast(JSON.toJSONString(msg).getBytes());
                }
            }
        }
    }


    void sendBroadcast(byte[] command){
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                        InetSocketAddress inetAddr = new InetSocketAddress(inetAddress, 0);
                        //2.获取广播socket
                        DatagramSocket socket = new DatagramSocket(inetAddr);
                        socket.setBroadcast(true);

                        //3.封装数据包
                        /*public DatagramPacket(byte[] buf,int length
                         *      ,InetAddress address
                         *      ,int port)
                         * buf：缓存的命令
                         * length：每次发送的数据字节数，该值必须小于等于buf的大小
                         * address：广播地址
                         * port：广播端口
                         */
                        DatagramPacket packet = new DatagramPacket(command, command.length, InetAddress.getByName("255.255.255.255"), 13453);
                        //4.发送数据
                        socket.send(packet);
                        //5.关闭socket
                        socket.close();
                    }
                }
            }
        } catch (UnknownHostException e) {
            //Ip地址错误时候抛出的异常
            e.printStackTrace();
        } catch (IOException e) {
            //获取socket失败时候抛出的异常
            e.printStackTrace();
        }
    }



    private void startQueueRead() {

        cmdSendTimer = new Timer();
        cmdSendTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                synchronized (queueZigbeeCodes) {
                    if (queueZigbeeCodes != null && queueZigbeeCodes.size() > 0) {
                        QueueZigbeeCode queueZigbeeCode = queueZigbeeCodes.get(0);
                        if (queueZigbeeCode.getTime() <= System.currentTimeMillis()) {
                            if (queueZigbeeCodes.size() > 0) {
                                queueZigbeeCodes.remove(0);
                            }
                            sendMessageToDevice(queueZigbeeCode.getHexCode());
                        }
                    }
                }
            }
        }, 0, 700);
    }
}
